import re
from source.py.feature import (
    generate_fea_string,
    generate_fea_string_cn_only,
    get_all_calt_text,
    get_cv_desc,
    get_cv_italic_desc,
    get_cv_cn_desc,
    get_freeze_moving_rules,
    get_ss_desc,
    get_total_feat_dict,
)
from source.py.feature import normal_enabled_features
from source.py.task._utils import read_json, read_text, write_json, write_text
from source.py.utils import joinPaths


def replace_section(md_path: str, border: str, content: str) -> None:
    md_content = read_text(md_path)
    pattern = f"{border}(.*){border}"
    updated_content = re.sub(
        pattern, f"{border}\n{content}\n{border}", md_content, flags=re.DOTALL
    )
    write_text(md_path, updated_content)


def update_feature_freeze(
    file_path: str,
    features: dict[str, str],
) -> None:
    config = read_json(file_path)
    config["feature_freeze"] = {tag: "ignore" for tag in features}
    write_json(file_path, config)


def update_schema(file_path: str, features: dict[str, str]) -> None:
    schema = read_json(file_path)
    schema["properties"]["feature_freeze"]["properties"] = {
        tag: {"description": desc, "$ref": "#/definitions/freeze_options"}
        for tag, desc in features.items()
    }
    write_json(file_path, schema)


def fea(output: str) -> None:
    # Generate feature files
    banner = "Auto generated by `python task.py fea`"
    files = {
        "regular.fea": generate_fea_string(is_italic=False, is_cn=False),
        "italic.fea": generate_fea_string(is_italic=True, is_cn=False),
        "cn.fea": generate_fea_string_cn_only(),
    }
    for filename, content in files.items():
        write_text(joinPaths(output, filename), f"# {banner}\n\n{content}")

    files_cn = {
        "regular_cn.fea": generate_fea_string(is_italic=False, is_cn=True),
        "italic_cn.fea": generate_fea_string(is_italic=True, is_cn=True),
    }
    for filename, content in files_cn.items():
        fea_path = joinPaths(output, filename)
        write_text(fea_path, f"# {banner}\n\n{content}")

    # Update README sections
    md_path = joinPaths(output, "README.md")
    sections = {
        "<!-- CALT -->": get_all_calt_text(),
        "<!-- CV -->": get_cv_desc(),
        "<!-- CV-IT -->": get_cv_italic_desc(),
        "<!-- CV-CN -->": get_cv_cn_desc(),
        "<!-- SS -->": get_ss_desc(),
    }
    for border, content in sections.items():
        replace_section(md_path, border, content)

    # Update configuration files
    features = get_total_feat_dict()

    update_schema(joinPaths("source", "schema.json"), features)
    update_feature_freeze("config.json", features)
    feat_str = ", ".join(normal_enabled_features)
    for f in ["README.md", "README_CN.md", "README_JA.md"]:
        replace_section(f, "<!-- NORMAL -->", f"```\n{feat_str}\n```")

    script_path = joinPaths("source", "py", "in_browser.py")
    in_browser_script = read_text(script_path)
    rules = get_freeze_moving_rules()
    rules.sort()
    rule_arr_text = "[" + ", ".join([f'"{item}"' for item in rules]) + "]"
    patched = re.sub(
        r"MOVING_RULES = .*",
        f"MOVING_RULES = {rule_arr_text}",
        in_browser_script,
    )
    write_text(script_path, patched)
